import { ROOT, useTransaction } from "@sker/core"
import { readdir } from 'fs-extra'
import { join } from "path";
import { SysAddon } from "@sker/entities";
import { DependencyContainer } from 'tsyringe'
import { z } from "zod";
import { useReqQuery } from "@sker/runtime";
export default async (injector: DependencyContainer) => {
    const input = z.object({
        current: z.optional(z.string()),
        pageSize: z.optional(z.string()),
        status: z.optional(z.string()),
    })
    const query = input.parse(useReqQuery())
    const { current = `1`, pageSize = `20`, status = 'all' } = query;
    const page = parseInt(current)
    const psize = parseInt(pageSize)
    let list = await useTransaction(async m => {
        const root = injector.resolve(ROOT)
        const addonRoot = join(root, 'addons')
        const scopes = await readdir(addonRoot)
        const addons = await Promise.all(scopes.map(async scope => {
            const addons = await readdir(join(addonRoot, scope))
            return await Promise.all(addons.map(async addon => {
                try {
                    const item = new SysAddon()
                    item.name = `${scope}/${addon}`
                    const pkg = require(join(addonRoot, scope, addon, 'package.json'))
                    item.title = pkg.title;
                    item.version = pkg.version;
                    item.desc = pkg.description;
                    const sysAddon = await m.findOne(SysAddon, { where: { name: item.name } })
                    if (!sysAddon) {
                        Reflect.set(item, 'status', 'uninstall')
                    } else {
                        Reflect.set(item, 'status', 'installed')
                    }
                    return item;
                } catch (e) {
                    return;
                }
            }))
        })).then(res => res.flat().filter(it=>!!it).map((item, index) => {
            item.aid = index;
            return item;
        }))
        return addons
    })
    if (status === 'all') {
    } else {
        list = list.filter(it => it.status === status)
    }
    const total = list.length;
    return {
        data: list.splice((page - 1) * psize, psize),
        total: total,
    }
}
